﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using AEM.Basic;
using AEM.Common;
using AEM.Controls;
using AEM.Data;
using AEM.Properties;
using AEM.Utils;
using Microsoft.Win32;
using Actions = AEM.Data.BLL.Actions;

namespace AEM
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
            this.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
            this.WindowState = WindowState.Maximized;
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);

            #region 系统设置 菜单 事件
            this.btn_sys_setting.Click += new RoutedEventHandler(btn_sys_setting_Click);
            this.btn_group_monitoring.Click += new RoutedEventHandler(btn_group_monitoring_Click);
            //this.btn_status_replay.Click += new RoutedEventHandler(btn_status_replay_Click);
            this.btn_data_statistics.Click += new RoutedEventHandler(btn_data_statistics_Click);
            #region 系统设置 子菜单
            this.btn_manularrange.Tag = false;//true可拖动排列,false不可拖动排列
            this.btn_manularrange.Click += new RoutedEventHandler(btn_manularrange_Click);
            this.btn_autoarrange.Click += new RoutedEventHandler(btn_autoarrange_Click);
            this.btn_importimage.Click += new RoutedEventHandler(btn_importimage_Click);
            this.btn_importlogo.Click += new RoutedEventHandler(btn_importlogo_Click);
            this.btn_liftstatus_add.Click += new RoutedEventHandler(btn_liftstatus_add_Click);
            this.btn_liftstatuspoints_add.Click += new RoutedEventHandler(btn_liftstatuspoints_add_Click);
            this.btn_liftinfo_add.Click += new RoutedEventHandler(btn_liftinfo_add_Click);
            this.btn_faultinfo_add.Click += new RoutedEventHandler(btn_faultinfo_add_Click);
            this.btn_defined_add.Click += new RoutedEventHandler(btn_defined_add_Click);
            this.btn_userinfo_add.Click += new RoutedEventHandler(btn_userinfo_add_Click);
            //this.btn_clientconfig_edit.Click += new RoutedEventHandler(btn_clientconfig_edit_Click);
            this.btn_smsphone.Click += new RoutedEventHandler(btn_smsphone_Click);
            this.btn_peeksetting.Click += new RoutedEventHandler(btn_peeksetting_Click);
            this.btn_modbusport.Click += new RoutedEventHandler(btn_modbusport_Click);
            this.btn_liftinline.Click += new RoutedEventHandler(btn_liftinline_Click);
            this.btn_statements.Click += new RoutedEventHandler((object o, RoutedEventArgs args) => { this.statements1.Visibility = Visibility.Visible; });
            this.btn_operationlog.Click += new RoutedEventHandler((object o, RoutedEventArgs args) => { this.operationlog.Visibility = Visibility.Visible; });
            this.btn_connectionstate.Click += new RoutedEventHandler((object o, RoutedEventArgs args) => { this.connectionState.Visibility = Visibility.Visible; });
            //this.btn_firegather.Click += new RoutedEventHandler(btn_firegather_Click);
            this.btn_password_edit.Click += new RoutedEventHandler(btn_password_edit_Click);
            this.btn_sys_exit.Click += new RoutedEventHandler(btn_sys_exit_Click);
            #endregion
            #endregion

            #region 分组监控 菜单 事件
            //this.btn_group_all.Click += new RoutedEventHandler(btn_group_all_Click);

            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo13") as string);
            //初始化添加查看分组按钮
            InitGroupButton();
            //btn_group_all.Visibility = Visibility.Collapsed;
            #endregion

            #region 状态回放 菜单 事件

            #endregion

            #region 数据统计 菜单 事件
            this.btn_fault_log.Click += new RoutedEventHandler(btn_fault_log_Click);
            this.btn_status_log.Click += new RoutedEventHandler(btn_status_log_Click);
            #endregion

            //窗口浮动 状态类型
            double stop = System.Windows.SystemParameters.WorkArea.Height - this.statements1.Height - 50;
            double sleft = System.Windows.SystemParameters.WorkArea.Width - this.statements1.Width;
            this.statements1.Margin = new Thickness(sleft, stop, 0, 0);
            this.statements1.Close += new EventHandler((object o, EventArgs args) => { (o as Statements).Visibility = Visibility.Hidden; });
            //窗口浮动 操作日志
            double otop = System.Windows.SystemParameters.WorkArea.Height - this.operationlog.Height - 50;
            this.operationlog.Margin = new Thickness(50, otop, 0, 0);
            this.operationlog.Close += new EventHandler((object o, EventArgs args) => { (o as OperationLog).Visibility = Visibility.Hidden; });
            //this.operationlog.Opacity = 0;
            //窗口浮动 连接状态统计
            double ctop = System.Windows.SystemParameters.WorkArea.Height - this.connectionState.Height - 50;
            this.connectionState.Margin = new Thickness(500, ctop, 0, 0);
            this.connectionState.Close += new EventHandler((object o, EventArgs args) => { (o as ConnectionState).Visibility = Visibility.Hidden; });

        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.lbVersion.Content = "AEM Copyright(C) 2023 v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo02") as string);
            //语言设置 菜单
            InitLangsMenu();
            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo03") as string);
            //设置权限
            SetPower();
            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo04") as string);
            //加载用户LOGO
            LoadUserLogo();

            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo05") as string);
            InitLiftInLineWindow();

            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo06") as string);
            LoadMonitoringWindow();

            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo07") as string);
            InitGatherFireWindow();

            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo08") as string);
            ///初始化，加载界面，电梯等
            InitScreen();

            #region 注册各种要老命的委托
            //注册主界面上电梯运行监控的委托
            Actions.LiftInfo.LiftRun = LiftRuning;
            Actions.LiftInfo.LiftRunInGroup = doLiftRunInGroup;
            Actions.LiftInfo.LiftRunNC = doLiftRunNC;
            //配置信息变更后调用的重载界面的委托
            Actions.LiftInfo.ReLoadUI = doReLoadUI;
            //单台电梯 复位按钮声音接纳调用的委托
            Actions.LiftInfo.ResetAlarm = doResetAlarm;
            Actions.PeakSetting.Reload = LoadPeakSetting;
            #endregion

            DispatcherTimer t = new DispatcherTimer();
            t.Interval = TimeSpan.FromMilliseconds(50);
            t.Tick += new EventHandler((sd, ev) =>
            {
                lbTimer.Content = DateTime.Now.ToString("yyyy-MM-dd   HH:mm:ss");
            });
            t.Start();
            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo10") as string);
            //加载高峰运行设置
            PeakMonitoring.Init();
            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo11") as string);
            //启动Modbus服务
            ModbusMonitoring.Init();
            MessageListener.Instance.ReceiveMessage(this.TryFindResource("LoadingInfo12") as string);
            //注册COM
            PortMonitoring.Init();

            Splasher.CloseSplash();
            PortMonitoring.Start();
        }

        private void LoadUserLogo()
        {
            ImageSource logo = Actions.ImageProcessor.LoadLogo();
            if (null != logo)
            {   if(logo.Width>= logo.Height)
                {
                    this.userlogo.Width = logo.Width> 200 ? 200 : logo.Width;
                    this.userlogo.Height = logo.Height / (logo.Width / 200);//> 150 ? 150 : logo.Height;
                }
                else
                {
                    this.userlogo.Height = logo.Height > 200 ? 200 : logo.Height;
                    this.userlogo.Width = logo.Width / (logo.Height / 200);//> 150 ? 150 : logo.Height;
                }
                //this.userlogo.Width = logo.Width;//> 150 ? 150 : logo.Width;
                //this.userlogo.Height = logo.Height;//> 150 ? 150 : logo.Height;
                this.userlogo.Source = logo;
                if (Common.PermissionManager.hasPower(-1))
                {
                    ContextMenu logoMenu = new ContextMenu();
                    MenuItem mi = new MenuItem();
                    mi.Header = this.TryFindResource("DeleteLogo") as string;// "删除用户Logo";
                    mi.Click += new RoutedEventHandler((ss, ee) =>
                    {
                        this.userlogo.Source = null;
                        Actions.ImageProcessor.DeleteLogo();
                    });
                    logoMenu.Items.Add(mi);
                    this.userlogo.ContextMenu = logoMenu;
                }
            }
        }

        private void LoadPeakSetting()
        {
            PeakMonitoring.Init();
        }

        private void InitScreen()
        {
            Dispatcher.Invoke(new Action(() =>
           {
               //清除已有的分屏按钮
               this.bar_split.Children.Clear();
               #region 超时10秒
               PortMonitoring._runOut = new List<int[]>();
               #endregion
               #region 清除界面上已有电梯
               foreach (TabItem t in this.split_screen.Items)
               {
                   Grid g = t.Content as Grid;
                   IEnumerable<LiftMonitor> ie = g.Children.OfType<LiftMonitor>();
                   Array.ForEach<LiftMonitor>(ie.ToArray<LiftMonitor>(), new Action<LiftMonitor>((v) =>
                   {
                       this.UnregisterName(v.Name);
                       g.Children.Remove(v);
                   }));
               }
               this.split_screen.Items.Clear();
               #endregion
               #region 加载每屏信息

               if (null != Config.LiftInftList)
               {
                   IEnumerable<int> result = from Data.Model.LiftInfo r in Config.LiftInftList
                                             orderby r.Screen
                                             select r.Screen;
                   result = result.Distinct();
                   bool radselect = false;
                   string info = this.TryFindResource("LoadingInfo09") as string;
                   Array.ForEach<int>(result.ToArray<int>(), new Action<int>((s) =>
                   {

                       MessageListener.Instance.ReceiveMessage(string.Format(info, s));
                       //s:屏序号
                       RadioButton rad = new RadioButton();
                       rad.Tag = s;
                       rad.Click += new RoutedEventHandler(SplitButton_Click);
                       this.bar_split.Children.Add(rad);
                       if (!radselect) { rad.IsChecked = true; radselect = true; }

                       TabItem tab = new TabItem();
                       tab.Tag = s;
                       tab.Name = "tab" + s;
                       LoadLift(tab, s);

                       this.split_screen.Items.Add(tab);

                   }));
               }
               #endregion
               this.split_screen.SelectedIndex = 0;
           }));
        }

        #region 加载电梯监控元素
        /// <summary>
        /// 初始化主界面上的电梯信息
        /// tab.分屏
        /// s.分屏序号
        /// </summary>
        private void LoadLift(TabItem tab, int s)
        {
            _left = 100;
            _top = 10;
            Grid ship = new Grid();
            ImageBrush img = Actions.ImageProcessor.LoadBackgroud(s);
            if (null != img)
            {
                img.Stretch = Stretch.UniformToFill;
                ship.Background = img;
                if (Common.PermissionManager.hasPower(-1))
                {
                    ContextMenu tabMenu = new ContextMenu();
                    MenuItem mi = new MenuItem();
                    mi.Header = this.TryFindResource("DeleteBG");// "删除当前背景";
                    mi.Click += new RoutedEventHandler((ss, ee) =>
                    {
                        ship.Background = null;
                        Actions.ImageProcessor.DeleteBackgroud(s);
                    });
                    tabMenu.Items.Add(mi);
                    ship.ContextMenu = tabMenu;
                }
            }
            if (null != Config.LiftInftList)
            {
                IEnumerable<Data.Model.LiftInfo> result = from Data.Model.LiftInfo row in Config.LiftInftList
                                                          where row.Screen == s
                                                          orderby row.LiftNum
                                                          select row;
                foreach (Data.Model.LiftInfo row in result)
                {
                    if (null != row)
                    {
                        LiftMonitor lm = new LiftMonitor();
                        this.RegisterName("lm" + row.LiftNum, lm);
                        lm.Name = "lm" + row.LiftNum;
                        Style ld = (Style)this.TryFindResource("MonitorDirection");
                        switch ((Data.Enum.LiftType)row.LiftType)
                        {
                            case Data.Enum.LiftType.扶梯:
                                ld = (Style)this.TryFindResource("MonitorEscalatoNormal");
                                break;
                            case Data.Enum.LiftType.人行步道:
                                ld = (Style)this.TryFindResource("MonitorTrailsNormal");
                                lm.Angle = row.Angle;
                                break;
                        }
                        lm.LiftDirection = ld;
                        lm.LiftStatus = GetLiftStatus(Data.Enum.LiftStatus.NC);
                        lm.LiftFloor = "";
                        lm.LiftName = row.LiftSite;
                        lm.ShortName = row.ShortName;
                        lm.Tag = row;
                        lm.MouseDoubleClick += new MouseButtonEventHandler(liftMonitor_MouseDoubleClick);
                        lm.MouseLeftButtonDown += new MouseButtonEventHandler(liftMonitor_MouseLeftButtonDown);
                        lm.HorizontalAlignment = HorizontalAlignment.Left;
                        lm.VerticalAlignment = VerticalAlignment.Top;
                        SetMargin(ref lm, row.Margin);
                        ship.Children.Add(lm);

                        #region 超时10秒
                        int[] runout = new int[3];
                        runout[0] = row.LiftNum;
                        runout[1] = row.LiftGroup;
                        runout[2] = 0;
                        PortMonitoring._runOut.Add(runout);
                        #endregion

                        connectionState.AddStateNC(row.LiftNum);
                    }
                }
            }
            tab.Content = ship;
        }

        #region 设置主界面上电梯排列位置
        double _left = 100;
        double _top = 10;
        void SetMargin(ref LiftMonitor lm)
        {
            double left = _left;// / this.Width;
            double top = _top;// / (this.Height - 30);
            lm.Margin = new Thickness(left, top, 0, 0);
            _left += 200;
            if (_left > this.Width - 200)
            {
                _left = 100;
                _top += 100;
            }
        }
        void SetMargin(ref LiftMonitor lm, string margin)
        {
            if (Settings.Default.autoArrange)
            {
                SetMargin(ref lm);
            }
            else
            {
                string[] mr = margin.Split(',');
                double left = Convert.ToDouble(mr[0]) * this.Width;
                double top = Convert.ToDouble(mr[1]) * (this.Height - 30);
                if (0 >= left || 0 >= top) SetMargin(ref lm);
                else if (left > this.Width - 200 || top > this.Height - 100) SetMargin(ref lm);
                else lm.Margin = new Thickness(left, top, 0, 0);
            }
        }
        #endregion
        #region 打开单梯监控界面
        LiftMonitoring winLiftMonitoring = null;
        EscalatorMonitoring winEscalatorMonitoring = null;
        TrailsMonittoring winTrailsMonittoring = null;
        private void LoadMonitoringWindow()
        {
            winLiftMonitoring = new LiftMonitoring();
            winLiftMonitoring.Visibility = Visibility.Hidden;
            winLiftMonitoring.ShowInTaskbar = false;
            winLiftMonitoring.Topmost = false;
            winLiftMonitoring.Show();
            winLiftMonitoring.HideEventHandler += new EventHandler<EventArgs>((s, ee) =>
            {
                winLiftMonitoring.Hide();
            });
            winLiftMonitoring.ContentRendered += new EventHandler((s, ee) =>
            {
                winLiftMonitoring.Hide();
            });
            winEscalatorMonitoring = new EscalatorMonitoring();
            winEscalatorMonitoring.Visibility = Visibility.Hidden;
            winEscalatorMonitoring.ShowInTaskbar = false;
            winEscalatorMonitoring.Topmost = false;
            winEscalatorMonitoring.Show();
            winEscalatorMonitoring.HideEventHandler += new EventHandler<EventArgs>((s, ee) =>
            {
                winEscalatorMonitoring.Hide();
            });
            winEscalatorMonitoring.ContentRendered += new EventHandler((s, ee) =>
            {
                winEscalatorMonitoring.Hide();
            });
            winTrailsMonittoring = new TrailsMonittoring();
            winTrailsMonittoring.Visibility = Visibility.Hidden;
            winTrailsMonittoring.Topmost = false;
            winTrailsMonittoring.ShowInTaskbar = false;
            winTrailsMonittoring.HideEventHandler += new EventHandler<EventArgs>((s, ee) =>
            {
                winTrailsMonittoring.Hide();
            });
            winTrailsMonittoring.ContentRendered += new EventHandler((s, ee) =>
            {
                winTrailsMonittoring.Hide();
            });
        }
        /// <summary>
        /// 双击主界面上电梯组件打开对应的监控界面
        /// </summary>
        private void liftMonitor_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            //if (!hasMonitorWin)
            //{
            LiftMonitor l = sender as LiftMonitor;
            Data.Model.LiftInfo r = l.Tag as Data.Model.LiftInfo;
            if (null != r)
            {
                //new Thread(new ThreadStart(() =>
                //{
                switch ((Data.Enum.LiftType)r.LiftType)
                {
                    case Data.Enum.LiftType.扶梯:
                        winEscalatorMonitoring.LiftID = r.ID;
                        winEscalatorMonitoring.ShowInTaskbar = true;
                        winEscalatorMonitoring.Topmost = true;
                        winEscalatorMonitoring.Show();
                        break;
                    case Data.Enum.LiftType.人行步道:
                        winTrailsMonittoring.LiftID = r.ID;
                        winTrailsMonittoring.ShowInTaskbar = true;
                        winTrailsMonittoring.Topmost = true;
                        winTrailsMonittoring.Show();
                        break;
                    case Data.Enum.LiftType.电梯:
                    default:
                        winLiftMonitoring.LiftID = r.ID;
                        winLiftMonitoring.ShowInTaskbar = true;
                        winLiftMonitoring.Topmost = true;
                        winLiftMonitoring.Show();
                        break;
                }
                PortMonitoring.MonitoringIDSign = r.LiftNum;
                PortMonitoring.MonitoringSign = true;
                //    System.Windows.Threading.Dispatcher.Run();
                //})) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();

                //hasMonitorWin = true;
                //  }
            }
        }
        bool hasMonitorWin = false;
        void Monitor_Closed(object sender, EventArgs e)
        {
            PortMonitoring.MonitoringIDSign = -1;
            hasMonitorWin = false;
            (sender as Window).Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
        }
        #endregion

        /// <summary>
        /// LiftRuning调用 获取电梯状态 样式
        /// </summary>
        private Style GetLiftStatus(Data.Enum.LiftStatus ls)
        {
            switch (ls)
            {
                case Data.Enum.LiftStatus.Fault:
                    return (Style)this.TryFindResource("MonitorStatusFault");
                case Data.Enum.LiftStatus.Driver:
                    return (Style)this.TryFindResource("MonitorStatusDriver");
                case Data.Enum.LiftStatus.Fire:
                    return (Style)this.TryFindResource("MonitorStatusFire");
                case Data.Enum.LiftStatus.Locked:
                    return (Style)this.TryFindResource("MonitorStatusLocked");
                case Data.Enum.LiftStatus.NC:
                    return (Style)this.TryFindResource("MonitorStatusNC");
                case Data.Enum.LiftStatus.Overhaul:
                    return (Style)this.TryFindResource("MonitorStatusOverhaul");
                case Data.Enum.LiftStatus.Standby:
                    return (Style)this.TryFindResource("MonitorStatusStandby");
                case Data.Enum.LiftStatus.Normal:
                default:
                    return (Style)this.TryFindResource("MonitorStatusNormal");
            }
        }
        #endregion

        void liftMonitor_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            doResetAlarm();
        }
        /// <summary>
        /// 委托,由单台电梯监控界面复位按钮调用 声音接纳
        /// </summary>
        void doResetAlarm()
        {
            if (null != PortMonitoring.alarmPlayer)
            {
                PortMonitoring.alarmPlayer.Stop();
                PortMonitoring.alarmPlayer.Dispose();
                PortMonitoring.alarmPlayer = null;
                PortMonitoring.isPlayingAlarm = true;
            }
        }

        #region 实现各种要老命的委托
        /// <summary>
        /// 电梯运行委托
        /// </summary>
        /// <param name="e"></param>
        private void LiftRuning(SerialDataEventArgs e)
        {
            if (null == e || null == e.Data) return;
            PortMonitoring.LiftRunSign[e.LiftNum - 1] = true;
            //电梯状态
            Data.Enum.LiftStatus ls = Data.Enum.LiftStatus.Normal;
            if (e.Data.Dirver) ls = Data.Enum.LiftStatus.Driver;
            if (e.Data.Overhaul) ls = Data.Enum.LiftStatus.Overhaul;
            if (e.Data.Locked) ls = Data.Enum.LiftStatus.Locked;
            if (e.Data.Fire) ls = Data.Enum.LiftStatus.Fire;
            if (e.Data.Standby) ls = Data.Enum.LiftStatus.Standby;
            if (e.Data.FaultLamp || e.Data.ConverterAlarm || e.Data.CageAlarm || e.Data.IsEarthquaked) ls = Data.Enum.LiftStatus.Fault;

            Dispatcher.Invoke(new Action(() =>
            {
                LiftMonitor l = (LiftMonitor)this.FindName("lm" + e.LiftNum);
                if (null == l) return;
                Data.Model.LiftInfo r = l.Tag as Data.Model.LiftInfo;
                if ((Data.Enum.LiftType)r.LiftType == Data.Enum.LiftType.电梯)
                    l.LiftFloor = e.FloorShow;
                l.LiftStatus = GetLiftStatus(ls);
                #region 上下行
                Style lds = (Style)this.TryFindResource("MonitorDirection"); ;
                if (null != r)
                {
                    //门方向,true上行;false下行;
                    switch ((Data.Enum.LiftType)r.LiftType)
                    {
                        case Data.Enum.LiftType.电梯:
                            if (e.Data.Rising)
                                lds = (Style)this.TryFindResource("MonitorLiftUp");
                            else if (e.Data.Descending)
                                lds = (Style)this.TryFindResource("MonitorLiftDown");
                            break;
                        case Data.Enum.LiftType.扶梯:
                            lds = (Style)this.TryFindResource("MonitorEscalatoNormal");
                            if (e.Data.Rising)
                                lds = (Style)this.TryFindResource("MonitorEscalatoUp");
                            else if (e.Data.Descending)
                                lds = (Style)this.TryFindResource("MonitorEscalatoDown");
                            break;
                        case Data.Enum.LiftType.人行步道:
                            lds = (Style)this.TryFindResource("MonitorTrailsNormal");
                            if (e.Data.Rising)
                                lds = (Style)this.TryFindResource("MonitorTrailsUp");
                            else if (e.Data.Descending)
                                lds = (Style)this.TryFindResource("MonitorTrailsDown");
                            break;
                    }
                }
                l.LiftDirection = lds;
                #endregion

                connectionState.CountState(e);
            }));
            if (e.Data.Fire)
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    this.btn_firegather_Click(null, null);
                }));
            }
            if (hasGatherFireWin && null != Actions.LiftInfo.LiftRunInGatherFire)
                Actions.LiftInfo.LiftRunInGatherFire.BeginInvoke(e, new AsyncCallback(Actions.LiftInfo.MonitoringCallback), null);

        }

        private void doLiftRunInGroup(SerialDataEventArgs e)
        {
            if (null == e || null == e.Data) return;
            PortMonitoring.GroupRunSign[e.LiftNum - 1] = true;
            Dispatcher.Invoke(new Action(() =>
            {
                GroupControl gc = (GroupControl)this.FindName("gc" + e.LiftInfo.LiftGroup);
                if (null == gc) return;
                gc.LiftRuning = e;
            }));
        }

        private void doLiftRunNC(int liftnum, int gid)
        {
            PortMonitoring.LiftRunSign[liftnum - 1] = false;
            PortMonitoring.GroupRunSign[liftnum - 1] = false;
            LiftMonitor l = (LiftMonitor)this.FindName("lm" + liftnum);
            if (null == l) return;
            l.LiftStatus = GetLiftStatus(Data.Enum.LiftStatus.NC);
            var g = (GroupControl)this.FindName("gc" + gid);
            if (null != g)
                g.LiftNC = liftnum;
            connectionState.AddStateNC(liftnum);
        }

        void doReLoadUI()
        {
            return;
            try
            {
                PortMonitoring.Stop();
                if (null != PortMonitoring.sports)
                    foreach (SerialPortManager sp in PortMonitoring.sports)
                        sp.Dispose();
                InitScreen();
                this.Dispatcher.Invoke(new Action(() =>
                {
                    InitGroupButton();
                    InitLiftInLineWindow();
                    InitGatherFireWindow();
                }));
                if (null != PortMonitoring.commandData)
                    foreach (var c in PortMonitoring.commandData)
                        c.Clear();
                PortMonitoring.Init();
            }
            catch (Exception ex)
            { Log.WriteError(ex.Message, ex); }
            if (null != Actions.LiftInfo.ResetConnectionState)
                Actions.LiftInfo.ResetConnectionState.Invoke();
        }

        #endregion

        /// <summary>
        /// 分屏切换按钮事件
        /// </summary>
        void SplitButton_Click(object sender, RoutedEventArgs e)
        {
            int index = this.bar_split.Children.IndexOf(sender as RadioButton);
            this.split_screen.SelectedIndex = index;
        }

        /// <summary>
        /// 故障统计
        /// </summary>
        void btn_fault_log_Click(object sender, RoutedEventArgs e)
        {
            new Thread(new ThreadStart(() =>
            {
                FaultLog win = new FaultLog();
                win.Closed += new EventHandler(Win_Close);
                win.ShowDialog();
                System.Windows.Threading.Dispatcher.Run();
            })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
        }

        /// <summary>
        /// 各种状态统计,
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_status_log_Click(object sender, RoutedEventArgs e)
        {
            new Thread(new ThreadStart(() =>
            {
                HallCallLog win = new HallCallLog();
                win.Closed += new EventHandler(Win_Close);
                win.ShowDialog();
                System.Windows.Threading.Dispatcher.Run();
            })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
        }

        /// <summary>
        /// 退出系统
        /// </summary>
        void btn_sys_exit_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBoxResult.Yes != MessageBox.Show(this.TryFindResource("ExitMessage") as string, this.TryFindResource("MessageBoxTitle") as string, MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No))
                return;

            Application.Current.Shutdown();
        }

        #region 初始化语言切换菜单
        private void InitLangsMenu()
        {
            this.langs_mothership.Children.Clear();
            DirectoryInfo dir = new System.IO.DirectoryInfo(System.IO.Path.GetFullPath("langs"));
            foreach (FileInfo f in dir.GetFiles("*.xaml"))
            {
                Image i = new Image();
                i.Tag = "langs/" + f.Name;
                string name = f.Name;
                name = name.Replace(f.Extension, "");
                i.ToolTip = name;
                i.Source = GetLangsIcon(f.DirectoryName, name);
                i.Width = 45;
                i.Height = 25;
                i.Margin = new Thickness(0, 0, 10, 0);
                i.Cursor = Cursors.Hand;
                i.MouseLeftButtonDown += new MouseButtonEventHandler(langs_MouseLeftButtonDown);
                this.langs_mothership.Children.Add(i);
            }
        }

        private ImageSource GetLangsIcon(string path, string name)
        {
            string pngpath = System.IO.Path.Combine(path, name + ".png");
            if (File.Exists(pngpath))
                return new BitmapImage(new Uri(pngpath));
            return new BitmapImage();
        }

        void langs_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (MessageBoxResult.Yes == MessageBox.Show(this.TryFindResource("ChangLangsInfo") as string, this.TryFindResource("MessageBoxTitle") as string, MessageBoxButton.YesNo, MessageBoxImage.Question))
            {
                Image i = sender as Image;
                Settings.Default.langs = i.Tag as string;
                Settings.Default.Save();
                Utils.LanguageHelper.LoadLanguageFile();
                Application.Current.Shutdown(); ;
            }
        }
        #endregion

        /// <summary>
        /// 菜单权限
        /// </summary>
        private void SetPower()
        {
            if (!PermissionManager.hasPower((int)Data.Enum.ControlPoints.DataStatistics))
            {
                //this.data_statistics_content.Children.Remove(this.btn_fault_log);
                this.btn_fault_log.Visibility=Visibility.Collapsed;//故障统计
                this.btn_status_log.Visibility = Visibility.Collapsed;//交通流量分析
                
            }
            if (!PermissionManager.hasPower((int)Data.Enum.ControlPoints.ApplicationLogs))
            {
                this.operationlog.Visibility = Visibility.Collapsed;
                this.btn_operationlog.Visibility = Visibility.Collapsed;
            }
            if (!PermissionManager.hasPower((int)Data.Enum.ControlPoints.ConnectionStatus))
            {
                this.connectionState.Visibility = Visibility.Collapsed;
                this.btn_connectionstate.Visibility = Visibility.Collapsed;
            }
            if (!PermissionManager.hasPower(-1))
            {
                this.btn_autoarrange.Visibility = Visibility.Collapsed;
                this.btn_manularrange.Visibility = Visibility.Collapsed;
                this.btn_importimage.Visibility = Visibility.Collapsed;
                this.btn_importlogo.Visibility = Visibility.Collapsed;
                this.btn_liftstatus_add.Visibility = Visibility.Collapsed;
                this.btn_liftinfo_add.Visibility = Visibility.Collapsed;
                this.btn_liftstatuspoints_add.Visibility = Visibility.Collapsed;
                this.btn_faultinfo_add.Visibility = Visibility.Collapsed;
                this.btn_userinfo_add.Visibility = Visibility.Collapsed;
                this.btn_smsphone.Visibility = Visibility.Collapsed;
                this.btn_peeksetting.Visibility = Visibility.Collapsed;
                this.btn_faultinfo_add.Visibility = Visibility.Collapsed;
                this.btn_modbusport.Visibility = Visibility.Collapsed;
                this.btn_defined_add.Visibility = Visibility.Collapsed;
            }
        }

        #region 系统设置 子菜单 事件

        /// <summary>
        /// modbus端口设置
        /// </summary>
        void btn_modbusport_Click(object sender, RoutedEventArgs e)
        {
            if (!hasModbusPortWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    ModbusPort win = new ModbusPort();
                    win.Closed += new EventHandler(ModbusPort_Closed);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasModbusPortWin = true;
            }
        }
        bool hasModbusPortWin = false;
        void ModbusPort_Closed(object sender, EventArgs e)
        {
            hasModbusPortWin = false;
            Win_Close(sender, e);
        }
        /// <summary>
        /// 高峰运行设置
        /// </summary>
        void btn_peeksetting_Click(object sender, RoutedEventArgs e)
        {
            if (!hasPeekSettingWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    PeakSetting win = new PeakSetting();
                    win.Closed += new EventHandler(PeekSetting_Closed);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasPeekSettingWin = true;
            }
        }
        bool hasPeekSettingWin = false;
        void PeekSetting_Closed(object sender, EventArgs e)
        {
            hasPeekSettingWin = false;
            Win_Close(sender, e);
        }
        /// <summary>
        /// 火警专用屏
        /// </summary>
        GatherFire winGatherFire = null;
        void btn_firegather_Click(object sender, RoutedEventArgs e)
        {
            //if (!hasGatherFireWin)
            //{
            //    if (null != winGatherFire)
            //    {
            //        winGatherFire.ShowInTaskbar = true;
            //        winGatherFire.Show();
            //        hasGatherFireWin = true;
            //    }
            //    else
            //    {
            //        InitGatherFireWindow();
            //        btn_firegather_Click(sender, e);
            //    }
            //}
        }

        private void InitGatherFireWindow()
        {
            //winGatherFire = new GatherFire();
            //winGatherFire.Visibility = Visibility.Hidden;
            //winGatherFire.ShowInTaskbar = false;
            //winGatherFire.Show();
            //winGatherFire.HideEventHandler += new EventHandler<EventArgs>((s, ee) =>
            //{
            //    hasGatherFireWin = false;
            //    winGatherFire.Hide();
            //});
            //winLiftInLine.ContentRendered += new EventHandler((s, ee) =>
            //{
            //    winGatherFire.Hide();
            //    hasGatherFireWin = false;
            //});
        }
        bool hasGatherFireWin = false;
        void GatherFire_Closed(object sender, EventArgs e)
        {
            hasGatherFireWin = false;
            //Win_Close(sender, e);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        void btn_password_edit_Click(object sender, RoutedEventArgs e)
        {
            new Thread(new ThreadStart(() =>
            {
                PassWord win = new PassWord();
                win.Closed += new EventHandler(Win_Close);
                win.ShowDialog();
                System.Windows.Threading.Dispatcher.Run();
            })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
        }
        /// <summary>
        /// 同线路电梯
        /// </summary>
        LiftInLine winLiftInLine = null;
        bool hideLiftInLine = false;
        void btn_liftinline_Click(object sender, RoutedEventArgs e)
        {
            if (hideLiftInLine && null != winLiftInLine)
            {

                winLiftInLine.Show();
                winLiftInLine.ShowInTaskbar = true;
            }
            else
            {
                InitLiftInLineWindow();
                btn_liftinline_Click(sender, e);
            }
        }

        private void InitLiftInLineWindow()
        {
            winLiftInLine = new LiftInLine();
            winLiftInLine.Visibility = Visibility.Hidden;
            winLiftInLine.ShowInTaskbar = false;
            winLiftInLine.Show();
            winLiftInLine.HideEventHandler += new EventHandler<EventArgs>((s, ee) =>
            {
                hideLiftInLine = true;
                winLiftInLine.Hide();
            });
            winLiftInLine.ContentRendered += new EventHandler((s, ee) =>
            {
                winLiftInLine.Hide();
                hideLiftInLine = true;
            });
        }
        /// <summary>
        /// 修改客户信息
        /// </summary>
        void btn_clientconfig_edit_Click(object sender, RoutedEventArgs e)
        {
            if (!hasClientConfigWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    ClientConfig win = new ClientConfig();
                    win.Closing += new System.ComponentModel.CancelEventHandler((ss, ee) =>
                    {
                        hasClientConfigWin = false;
                    });
                    win.Closed += new EventHandler(Win_Close);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasClientConfigWin = true;
            }
        }
        bool hasClientConfigWin = false;

        void btn_smsphone_Click(object sender, RoutedEventArgs e)
        {
            if (!hasSMSSettingWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    SMSSetting win = new SMSSetting();
                    win.Closing += new System.ComponentModel.CancelEventHandler((ss, ee) =>
                    {
                        hasSMSSettingWin = false;
                    });
                    win.Closed += new EventHandler(Win_Close);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasSMSSettingWin = true;
            }
        }
        bool hasSMSSettingWin = false;

        /// <summary>
        /// 用户帐户管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_userinfo_add_Click(object sender, RoutedEventArgs e)
        {
            if (!hasUserManageWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    UserManage win = new UserManage();
                    win.Closing += new System.ComponentModel.CancelEventHandler((ss, ee) =>
                    {
                        hasUserManageWin = false;
                    });
                    win.Closed += new EventHandler(Win_Close);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasUserManageWin = true;
            }
        }
        bool hasUserManageWin = false;
        /// <summary>
        /// 操作名称管理
        /// </summary>
        void btn_defined_add_Click(object sender, RoutedEventArgs e)
        {
            if (!hasDefinedInfoWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    DefinedInfo win = new DefinedInfo();
                    win.Closing += new System.ComponentModel.CancelEventHandler((ss, ee) =>
                    {
                        hasDefinedInfoWin = false;
                    });
                    win.Closed += new EventHandler(Win_Close);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasDefinedInfoWin = true;
            }
        }
        bool hasDefinedInfoWin = false;

        /// <summary>
        /// 故障信息编辑
        /// </summary>
        void btn_faultinfo_add_Click(object sender, RoutedEventArgs e)
        {
            if (!hasFaultDefinitionWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    FaultDefinition win = new FaultDefinition();
                    win.Closing += new System.ComponentModel.CancelEventHandler((ss, ee) =>
                    {
                        hasFaultDefinitionWin = false;
                    });
                    win.Closed += new EventHandler(Win_Close);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasFaultDefinitionWin = true;
            }
        }
        bool hasFaultDefinitionWin = false;
        /// <summary>
        /// 管理电梯信息
        /// </summary>
        void btn_liftinfo_add_Click(object sender, RoutedEventArgs e)
        {
            if (!hasLiftInfoWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    LiftInfo win = new LiftInfo();
                    win.Closing += new System.ComponentModel.CancelEventHandler((ss, ee) =>
                    {
                        hasLiftInfoWin = false;
                    });
                    win.Closed += new EventHandler(Win_Close);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasLiftInfoWin = true;
            }
        }
        bool hasLiftInfoWin = false;
        /// <summary>
        /// 管理状态点/型号库
        /// </summary>
        void btn_liftstatuspoints_add_Click(object sender, RoutedEventArgs e)
        {
            if (!hasLiftStatusPointsWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    LiftStatusPoints win = new LiftStatusPoints();
                    win.Closing += new System.ComponentModel.CancelEventHandler((ss, ee) =>
                    {
                        hasLiftStatusPointsWin = false;
                    });
                    win.Closed += new EventHandler(Win_Close);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasLiftStatusPointsWin = true;
            }
        }
        bool hasLiftStatusPointsWin = false;
        /// <summary>
        /// 管理状态信息
        /// </summary>
        void btn_liftstatus_add_Click(object sender, RoutedEventArgs e)
        {
            if (!hasLiftStatusWin)
            {
                new Thread(new ThreadStart(() =>
                {
                    LiftStatus win = new LiftStatus();
                    win.Closing += new System.ComponentModel.CancelEventHandler((ss, ee) =>
                    {
                        hasLiftStatusWin = false;
                    });
                    win.Closed += new EventHandler(Win_Close);
                    win.ShowDialog();
                    System.Windows.Threading.Dispatcher.Run();
                })) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();
                hasLiftStatusWin = true;
            }
        }
        bool hasLiftStatusWin = false;
        /// <summary>
        /// 导入背景图片
        /// </summary>
        void btn_importimage_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = this.TryFindResource("ImportImage") as string;// "导入背景图片";
            dlg.Filter = "BMP,JPG,JPEG,PNG|*.bmp;*.jpg;*.jpeg;*.png;";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                int screen = (int)(this.split_screen.SelectedItem as TabItem).Tag;
                string filename = dlg.FileName;
                ImageBrush newfile = Actions.ImageProcessor.ImportBackground(screen, filename, this.Width, this.Height - 30);
                if (null != newfile)
                {
                    newfile.Stretch = Stretch.UniformToFill;
                    Grid ship = (this.split_screen.SelectedItem as TabItem).Content as Grid;
                    ship.Background = newfile;
                    if (Common.PermissionManager.hasPower(-1))
                    {
                        ContextMenu tabMenu = new ContextMenu();
                        MenuItem mi = new MenuItem();
                        mi.Header = this.TryFindResource("DeleteBG");// "删除当前背景";
                        mi.Click += new RoutedEventHandler((ss, ee) =>
                        {
                            ship.Background = null;
                            Actions.ImageProcessor.DeleteBackgroud(screen);
                        });
                        tabMenu.Items.Add(mi);
                        ship.ContextMenu = tabMenu;
                    }
                }
            }
        }
        /// <summary>
        /// 导入LOGO
        /// </summary>
        void btn_importlogo_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = this.TryFindResource("ImportLogo") as string;// "导入Logo图片";
            dlg.Filter = "BMP,JPG,JPEG,PNG|*.bmp;*.jpg;*.jpeg;*.png;";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                ImageSource newfile = Actions.ImageProcessor.ImportLogo(filename, 0, 0);
                if (null != newfile)
                {
                    LoadUserLogo();
                }
            }
        }
        /// <summary>
        /// 自动排列
        /// </summary>
        void btn_autoarrange_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)btn_manularrange.Tag)
                btn_manularrange_Click(btn_manularrange, e);
            _left = 100;
            _top = 10;
            Settings.Default.autoArrange = true;
            Settings.Default.Save();
            try
            {
                IEnumerable<LiftMonitor> ie = (this.split_screen.SelectedContent as Grid).Children.OfType<LiftMonitor>();
                Array.ForEach<LiftMonitor>(ie.ToArray<LiftMonitor>(), new Action<LiftMonitor>((v) =>
                {
                    SetMargin(ref v);
                }));
            }
            catch { }
        }
        /// <summary>
        /// 手动排列
        /// </summary>
        void btn_manularrange_Click(object sender, RoutedEventArgs e)
        {
            _left = 100;
            _top = 10;
            Settings.Default.autoArrange = false;
            Settings.Default.Save();
            Button btn = (sender as Button);
            bool flag = (bool)btn.Tag;
            btn.Tag = !flag;
            try
            {
                IEnumerable<LiftMonitor> ls = (this.split_screen.SelectedContent as Grid).Children.OfType<LiftMonitor>();
                foreach (LiftMonitor lm in ls)
                {
                    lm.IsDragging = !flag;
                }
                if (flag)
                {
                    btn.Content = (string)this.TryFindResource("ManulArrange");
                    //以下保存 电梯位置
                    IEnumerable<LiftMonitor> ie = (this.split_screen.SelectedContent as Grid).Children.OfType<LiftMonitor>();
                    Array.ForEach<LiftMonitor>(ie.ToArray<LiftMonitor>(), new Action<LiftMonitor>((v) =>
                    {
                        double left = 0, top = 0;
                        left = v.Margin.Left;
                        top = v.Margin.Top;
                        left /= this.Width;
                        top /= (this.Height - 30);
                        Data.Model.LiftInfo row = (Data.Model.LiftInfo)v.Tag;
                        row.Margin = left.ToString("0.0000") + "," + top.ToString("0.0000");
                        v.Tag = row;
                        Actions.LiftInfo.ModifiyLiftMargin(row.ID, left, top);
                    }));
                    Config.LiftInftList = Actions.LiftInfo.List("");
                }
                else
                {
                    btn.Content = (string)this.TryFindResource("ManulArrangeEnd");
                    IEnumerable<LiftMonitor> ie = (this.split_screen.SelectedContent as Grid).Children.OfType<LiftMonitor>();
                    Array.ForEach<LiftMonitor>(ie.ToArray<LiftMonitor>(), new Action<LiftMonitor>((v) =>
                    {
                        Data.Model.LiftInfo row = (Data.Model.LiftInfo)v.Tag;
                        SetMargin(ref v, row.Margin);
                    }));
                }
            }
            catch { btn.Tag = flag; }
        }
        #endregion

        #region 主菜单 事件
        void btn_sys_setting_Click(object sender, RoutedEventArgs e)
        {
            playstory(sys_setting_content);
        }

        void btn_group_monitoring_Click(object sender, RoutedEventArgs e)
        {
            playstory(group_monitoring_content);
        }

        void btn_status_replay_Click(object sender, RoutedEventArgs e)
        {
            //playstory(status_replay_content);
        }

        void btn_data_statistics_Click(object sender, RoutedEventArgs e)
        {
            this.btn_data_statistics.Style = (Style)this.TryFindResource("menu_button_center");
            playstory(data_statistics_content);
        }

        void playstory(StackPanel sp)
        {
            Storyboard s = new Storyboard();
            DoubleAnimation da = new DoubleAnimation(0, TimeSpan.FromSeconds(0.5));
            Storyboard.SetTargetProperty(da, new PropertyPath("Height"));

            if (sp != sys_setting_content && 0 != sys_setting_content.Height)
                Storyboard.SetTargetName(da, sys_setting_content.Name);
            if (sp != group_monitoring_content && 0 != group_monitoring_content.Height)
                Storyboard.SetTargetName(da, group_monitoring_content.Name);
            //if (sp != status_replay_content && 0 != status_replay_content.Height)
            //    Storyboard.SetTargetName(da, status_replay_content.Name);
            if (sp != data_statistics_content && 0 != data_statistics_content.Height)
            {
                this.btn_data_statistics.Style = (Style)this.TryFindResource("menu_button_bottom");
                Storyboard.SetTargetName(da, data_statistics_content.Name);
            }

            s.Children.Add(da);
            if (0 == sp.Height)
            {
                DoubleAnimation d = new DoubleAnimation(568, TimeSpan.FromSeconds(0.5));
                Storyboard.SetTargetProperty(d, new PropertyPath("Height"));
                Storyboard.SetTargetName(d, sp.Name);
                s.Children.Add(d);
            }
            this.BeginStoryboard(s);

        }
        #endregion

        #region 初始化添加查看分组控件
        /// <summary>
        /// 初始化添加查看分组按钮
        /// </summary>
        private void InitGroupButton()
        {
            Dispatcher.Invoke(new Action(() =>
            {
                this.group_monitoring_content.Children.Clear();
                Button btnall = new Button();
                btnall.Style = (Style)this.TryFindResource("menu_button_normal");
                btnall.Content = (string)this.TryFindResource("GroupAll");
                btnall.Click += new RoutedEventHandler(btn_group_all_Click);
                this.group_monitoring_content.Children.Add(btnall);

                if (null == Config.LiftInftList) return;

                IEnumerable<int> result = from row in Config.LiftInftList
                                          where row.LiftType == (int)Data.Enum.LiftType.电梯
                                          orderby row.LiftGroup
                                          select row.LiftGroup;

                result = result.Distinct();
                string info = this.TryFindResource("LoadingInfo14") as string;
                Array.ForEach<int>(result.ToArray<int>(), new Action<int>((g) =>
                {
                    Button btn = new Button();
                    btn.Style = (Style)this.TryFindResource("menu_button_normal");
                    btn.Tag = g;
                    btn.Content = (string)this.TryFindResource("Group") + " " + g;
                    btn.Click += new RoutedEventHandler(GroupButton_Click);
                    this.group_monitoring_content.Children.Add(btn);

                    MessageListener.Instance.ReceiveMessage(string.Format(info, g));
                    LoadGroupControl(g);
                }));
            }));
        }

        /// <summary>
        /// 初始化添加查看分组控件
        /// </summary>
        void GroupButton_Click(object sender, RoutedEventArgs e)
        {
            int g = (int)(sender as Button).Tag;
            GroupControl gc = (GroupControl)this.group_mothership.FindName("gc" + g);
            if (null == gc)
            {
                LoadGroupControl(g);
            }
            else
                gc.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 打开同组监控
        /// </summary>
        void btn_group_all_Click(object sender, RoutedEventArgs e)
        {
            foreach (GroupControl gc in this.group_mothership.Children)
            {
                gc.Visibility = Visibility.Visible;
            }
        }

        private void LoadGroupControl(int g)
        {
            //new Thread(new ThreadStart(() =>
            // {
            GroupControl gc = (GroupControl)this.group_mothership.FindName("gc" + g);
            if (null != gc)
            {
                this.group_mothership.Children.Remove(gc);
                this.UnregisterName(gc.Name);
                gc = null;
            }
            Dispatcher.Invoke(new Action(() =>
            {
                Data.Model.GroupMargin model = Data.DAL.GroupMargin.Select("ID", g.ToString());

                string margin = null != model ? model.Margin : null;
                if (string.IsNullOrEmpty(margin)) margin = "0,0";
                string[] mr = margin.Split(',');
                double left = Convert.ToDouble(mr[0]);
                double top = Convert.ToDouble(mr[1]);

                gc = new GroupControl();
                this.RegisterName("gc" + g, gc);
                gc.Name = "gc" + g;
                gc.GroupID = g;
                gc.HorizontalAlignment = HorizontalAlignment.Left;
                gc.VerticalAlignment = VerticalAlignment.Top;
                gc.Margin = new Thickness(left, top, 0, 0);
                gc.CloseEventHandler += new EventHandler<EventArgs>(GroupControl_CloseEventHandler);
                gc.CompleteEventHandler += new EventHandler<EventArgs>(GroupControl_CompleteEventHandler);
                gc.MouseLeftButtonDown += new MouseButtonEventHandler((object sender, MouseButtonEventArgs e) =>
                {
                    gzindex++;
                    Grid.SetZIndex(gc, gzindex);
                });
                gc.Visibility = Visibility.Hidden;
                this.group_mothership.Children.Add(gc);
            }));
            //})) { Priority = ThreadPriority.AboveNormal, ApartmentState = ApartmentState.STA, IsBackground = true }.Start();

        }

        void GroupControl_CompleteEventHandler(object sender, EventArgs e)
        {

        }
        static int gzindex;

        void GroupControl_CloseEventHandler(object sender, EventArgs e)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                GroupControl gc = sender as GroupControl;
                if (null != gc) gc.Visibility = Visibility.Hidden;
                //try
                //{
                //    this.UnregisterName((sender as GroupControl).Name);
                //    this.group_mothership.Children.Remove((sender as GroupControl));
                //}
                //catch { }
            }));
        }

        #endregion

        void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            ModifierKeys modifiers = e.KeyboardDevice.Modifiers;

            if ((modifiers & ModifierKeys.Shift) != 0 && (modifiers & ModifierKeys.Control) != 0
                && (modifiers & ModifierKeys.Alt) != 0 && e.Key == Key.F12)
            {
                ConsoleManager.Toggle();
            }
        }

        void Win_Close(object sender, EventArgs e)
        {
            (sender as Window).Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
        }
    }
}
